package leetcode;

/**
 * Z 字形变换  
 */
public class LeetCode6 {
    public String convert(String s, int numRows) {
        if (s == null || s.length() == 0) {
            return "";
        }
        if (numRows == 1) {
            return s;
        }
        int len = s.length();
        StringBuilder res = new StringBuilder();
        for (int row = 0; row < numRows; row++) {
            int k = 0;
            if (row == 0) {
                while (k * (2 * numRows - 2) < len) {
                    res.append(s.charAt(k * (2 * numRows - 2)));
                    k++;
                }
            } else if (row == numRows - 1) {
                while (k * (2 * numRows - 2) + numRows - 1 < len) {
                    res.append(s.charAt(k * (2 * numRows - 2) + numRows - 1));
                    k++;
                }
            } else {
                boolean isEven = true;
                int index;
                do {
                    if (isEven) {
                        index = (k / 2) * (2 * numRows - 2) + row;
                    } else {
                        index = (k / 2) * (2 * numRows - 2) + row + 2 * (numRows - row - 1);
                    }
                    if (index < len) {
                        res.append(s.charAt(index));
                    }
                    isEven = !isEven;
                    k++;
                } while (index < len);
            }

        }

        return res.toString();
    }

    public static void main(String[] args) {
        LeetCode6 leetCode06 = new LeetCode6();
        System.out.println(leetCode06.convert("A", 1));
    }
}
